<template>
	<z-paging ref="paging" v-model="dataList" @query="queryList" :show-loading-more-no-more-view="false" default-page-size="20">
		<template slot="top">
			<cl-navbar :title="type == 'list'|| type == 'banned'?$t('group.group_members.title'):$t('group.common.pleaseSelectGroupMember')" leftIconSize="40rpx" placeholder autoBack>
				<template slot="right" v-if="type == 'manager' || type == 'remove'">
					<text style="font-size: 28rpx;" @click="complete">{{$t("group.common.complete")}}</text>
				</template>
			</cl-navbar>
			<view class="searchview" v-if="getPermission('can_add_friends') && !getHideMemberText">
				<u-search height="64rpx" :showAction="false" :clearabled="false" bgColor="#1e1f30" :inputStyle="{fontSize:'24rpx'}" :placeholder="$t('commonality.search')" @input="searchInput"></u-search>
			</view>
			<view class="prohibitSearch" v-else>
				<text v-if="!getPermission('can_add_friends') && getHideMemberText">{{$t("group.group_members.memberProtectionAll")}}</text>
				<text v-else-if="!getPermission('can_add_friends')">{{$t("group.group_members.memberProtection1")}}</text>
				<text v-else-if="getHideMemberText">{{$t("group.group_members.memberProtection2")}}</text>
			</view>
		</template>
		<view v-if="getShowList.managerData.length" style="padding: 10rpx 30rpx;" class="groupview">
			<span class="grouptitle">{{$t("group.group_members.ownerManage")}}</span>
			<template v-for="(item, index) in getShowList.managerData">
				<view class="listitem" @click="itemclick(item)" :key="index" v-if="item.role == 'creator' || item.role == 'manager'">
					<view class="listitem__left" v-if="type == 'manager' || type == 'remove'">
						<image src="/static/icon/select.png" mode="" style="width: 36rpx;height: 36rpx;opacity: 0.6" v-if="type == 'manager' && (item.role == 'manager' || item.role == 'creator')"></image>
						<image src="/static/icon/select.png" mode="" style="width: 36rpx;height: 36rpx;" v-else-if="selectData.includes(item.user_id)"></image>
						<image src="/static/icon/no-select.png" mode="" style="width: 36rpx;height: 36rpx;" v-else></image>
					</view>
					<view class="listitem__right">
						<cl-avatar :src="item.avatar_url" size="80rpx"></cl-avatar>
						<view class="listitem__right__view">
							<view class="listitem__right__view__nickname">
								<text>{{item.group_nickname || item.user_nickname}}</text>
								<text v-if="item.role == 'creator'" class="typetag" style="background-color: #52AAFF;">{{$t("group.common.creator")}}</text>
								<text class="typetag" v-if="item.role == 'manager'">{{$t("group.common.manage")}}</text>
								<text class="typetag" v-if="item.user_type && item.user_type > 0 && item.user_type != 6 && item.user_type != 8" style="background-color: #02D478;">{{$t("common.friend.authority")}}</text>
							</view>
							<view class="listitem__right__content">
								<text v-if="groupMemberOnline[item.user_id]"
									style="color: #6aaf76;font-size: 24rpx;">[{{$t("common.friend.online")}}]</text>
								<text v-else
									style="color: #595A66;font-size: 24rpx;">[{{$t("common.friend.offline")}}]</text>
								<text class="listitem__right__view__id">ID:{{getPermission('can_add_friends')?item.user_no:'******'}}</text>
							</view>
						</view>
					</view>
					<view v-if="type == 'banned'">
						<u-switch v-model="item.is_muted" asyncChange  @change="e=>setChangeMuted(item,e)" size="20"
							:activeValue="1" :inactiveValue="0" inactiveColor="#1e1f30"
							activeColor="#1e1f30"></u-switch>
					</view>
				</view>
			</template>
		</view>
		<view v-if="getShowList.memberData.length" style="padding: 10rpx 30rpx;" class="groupview">
			<span class="grouptitle">{{$t("group.group_members.member")}}</span>
			<template v-for="(item, index) in getShowList.memberData" >
				<view class="listitem" @click="itemclick(item)" :key="index" v-if="item.role != 'creator' && item.role != 'manager'">
					<view class="listitem__left" v-if="type == 'manager' || type == 'remove'">
						<image src="/static/icon/select.png" mode="" style="width: 36rpx;height: 36rpx;opacity: 0.6" v-if="type == 'manager' && (item.role == 'manager' || item.role == 'creator')"></image>
						<image src="/static/icon/select.png" mode="" style="width: 36rpx;height: 36rpx;" v-else-if="selectData.includes(item.user_id)"></image>
						<image src="/static/icon/no-select.png" mode="" style="width: 36rpx;height: 36rpx;" v-else></image>
					</view>
					<view class="listitem__right">
						<cl-avatar :src="item.avatar_url" size="80rpx"></cl-avatar>
						<view class="listitem__right__view">
							<view class="listitem__right__view__nickname">
								<text>{{item.group_nickname || item.user_nickname}}</text>
								<text v-if="item.role == 'creator'" class="typetag" style="background-color: #52AAFF;">{{$t("group.common.creator")}}</text>
								<text class="typetag" v-if="item.role == 'manager'">{{$t("group.common.manage")}}</text>
								<text class="typetag" v-if="item.user_type && item.user_type > 0 && item.user_type != 6 && item.user_type != 8" style="background-color: #02D478;">{{$t("common.friend.authority")}}</text>
							</view>
							<view class="listitem__right__content">
								<text v-if="groupMemberOnline[item.user_id]"
									style="color: #6aaf76;font-size: 24rpx;">[{{$t("common.friend.online")}}]</text>
								<text v-else
									style="color: #595A66;font-size: 24rpx;">[{{$t("common.friend.offline")}}]</text>
								<text class="listitem__right__view__id">ID:{{getPermission('can_add_friends')?item.user_no:'******'}}</text>
							</view>
						</view>
					</view>
					<view v-if="type == 'banned'">
						<u-switch v-model="item.is_muted" asyncChange :loading = "item.loading"  @change="e=>setChangeMuted(item,e)" size="20"
							:activeValue="1" :inactiveValue="0" inactiveColor="#1e1f30"
							activeColor="#1e1f30"></u-switch>
					</view>
				</view>
			</template>
		</view>
	</z-paging>
</template>

<script>
	// 定义排序规则的映射
	const roleOrder = {
	  'creator': 0,
	  'manager': 1,
	  'member': 2
	};
	
	import groupMembersApi from "@/services/api/group_members.js"
	
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'group_members',
		data() {
			return {
				searchval:'',
				group_id:'',
				type:'list',
				selectData:[],
				dataList:[],
			}
		},
		computed: {
			...mapState({
				groupInfo: state => state.chat.chatGroupInfo,
				groupMemberOnline: state => state.chat.groupMemberOnline,
			}),
			getPermission(){
				return (type)=>{
					if(this.groupInfo == null)return false
					// 0所有人 1普通用户 2管理员 3都不允许
					if(this.groupInfo[type] == '0'){
						return true
					}else if(this.groupInfo[type] == '1'){
						if(this.groupInfo.userRole && this.groupInfo.userRole != 'manager')return true
					}else if(this.groupInfo[type] == '2'){
						if(this.groupInfo.userRole && this.groupInfo.userRole != 'member')return true
					}else if(this.groupInfo[type] == '3'){
						if(this.groupInfo.userRole && this.groupInfo.userRole == 'creator')return true
					}
					return false
				}
			},
			getHideMemberText(){
				// show_member_list是否显示群成员
				//这里的逻辑是  是否隐藏群成员
				console.log(this.groupInfo['show_member_list']);
				if(this.groupInfo && this.groupInfo['show_member_list'] == '0' && this.groupInfo.userRole == 'member'){
					return true
				}
				return false
			},
			getShowList(){
				let managerData = [];
				let memberData = [];
				
				this.dataList.forEach(item => {
					if(item.role == 'creator' && this.type == 'list'){
						managerData.unshift(item);
					}else if(item.role == 'manager'){
						managerData.push(item);
					} else {
						memberData.push(item);
				    }
				});
				return {
					managerData,
					memberData
				}
			},
		},
		watch:{
			"groupInfo.mygroup": {
			  handler(newVal,oldVal) {
				 if(newVal == 0){
					this.$Router.back()
				 }
			  },
			  deep: true,
			}
		},
		onLoad() {
			let query = this.$Route.query
			if(query.type){
				this.type = query.type
			}
			if(query.group_id)this.group_id = query.group_id
			
			uni.$on('onGroupMemberAction',this.onGroupMemberAction)
		},
		onUnload() {
			uni.$off('onGroupMemberAction', this.onGroupMemberAction);
		},
		methods: {
			//监听群成员变化
			onGroupMemberAction(data){
				console.log(data);
				if(data.type == 'userInfo'){
					let index = this.dataList.findIndex(item => item.user_id == data.data.user_id);
					if (index !== -1) {
					  for (let key in data.data) {
					    if (data.data[key] != this.dataList[index][key]) {
					      Vue.set(this.dataList[index], key, data.data[key]);
					    }
					  }
					}
				}else if(data.type == 'delMember'){
					if (data.data.group_id == this.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
					            this.dataList.splice(index, 1);
					        }
					    });
					}
				}else if(data.type == 'quit'){
					if (data.data.group_id == this.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
					            this.dataList.splice(index, 1);
					        }
					    });
					}
				}else if(data.type == 'managerAdd'){
					if (data.data.group_id == this.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
								Vue.set(this.dataList[index], 'role', 'manager');
					        }
					    });
					}
				}else if(data.type == 'managerCancel'){
					if (data.data.group_id == this.group_id) {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
								Vue.set(this.dataList[index], 'role', 'member');
					        }
					    });
					}
				}else if(data.type == 'muted'){
					if (data.data.group_id == this.group_id && this.type == 'banned') {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
								Vue.set(this.dataList[index], 'is_muted', 1);
					        }
					    });
					}
				}else if(data.type == 'remove_muted'){
					if (data.data.group_id == this.group_id && this.type == 'banned') {
					    data.data.user_ids.forEach(member => {
					        let index = this.dataList.findIndex(item => item.user_id == member);
					        if (index !== -1) {
								Vue.set(this.dataList[index], 'is_muted', 0);
					        }
					    });
					}
				}else if(data.type == 'member_nick'){
					if (data.data.group_id == this.group_id) {
					    let index = this.dataList.findIndex(item => item.user_id == data.data.user_id);
					    if (index !== -1) {
					        Vue.set(this.dataList[index], 'group_nickname', data.data.group_nickname);
					    }
					}
				}
			},
			searchInput(e){
				uni.$u.debounce(()=>{
					this.searchval = e
					this.$refs.paging.reload()
				}, 500,false)
			},
			async queryList(pageNo, pageSize) {
				try{
					let memberRes = null
					//如果是列表或者是设置管理员或者是禁言并且我是群主
					if(this.type == 'list' || ((this.type == 'banned' || this.type == 'remove' || this.type == 'manager') && this.groupInfo.userRole == 'creator')){
						  memberRes = await groupMembersApi.getMemberListPage({
								group_id:this.group_id,
								page:pageNo,
								limit:pageSize,
								nick_name:this.searchval
						  })
					}else{//设置管理员
						memberRes = await groupMembersApi.getMembersListPage({
							group_id:this.group_id,
							page:pageNo,
							limit:pageSize,
							nick_name:this.searchval
						})
					}
					
					if (memberRes) {
						this.$refs.paging.complete(memberRes.list)
					} else {
						this.$refs.paging.complete(false)
					}
					
				}catch(e){
					//TODO handle the exception
				}
				
			},
			async complete(){
				if(!this.selectData.length){
					uni.showToast({
						title:this.$t("group.common.selectOneMember"),
						icon:'none'
					})
					return
				}
				switch (this.type){
					case 'manager':
					    try{
					    	let apires = await groupMembersApi.editRole(this.group_id,this.selectData,'manager')
					    	if(apires){
								//发送全局通知
								uni.$emit('onGroupMemberAction',{
									type:'managerAdd',
									data:{
										group_id:this.group_id,
										user_ids:this.selectData
									}
								})
					    		setTimeout(()=>{
					    			this.$Router.back(1)
					    		},1000)
					    	}
					    }catch(e){
					    	//TODO handle the exception
					    }
						
						break;
					case 'remove':
						let apires = await groupMembersApi.weedout(this.group_id,this.selectData)
						if(apires){
							setTimeout(()=>{
								this.$Router.back(1)
							},1000)
						}
						break;
					default:
						break;
				}
			},
			async setChangeMuted(item,val){
				try{
					this.$set(item,'loading',true)
					let apires = await groupMembersApi.muted(this.group_id,[item.user_id],val)
					if(apires){
						item.is_muted = val
					}
				}catch(e){
					//TODO handle the exception
				}
				this.$set(item,'loading',false)
			},
			async itemclick(item){
				
				if(this.type == 'list'){
					uni.$u.throttle(async()=>{
						if(item.user_id == this.$store.state.user.user_info.user_id)return
						if(!this.getPermission('can_add_friends')){
							uni.showToast({
								title:this.$t("group.group_members.memberBeingProtected"),
								icon:'none'
							})
							return
						}
						
						try{
							let friendRes = await uni.$api.friends.isFriend({friend_id:item.user_id})
							if(friendRes && friendRes.data.is_friend){
								this.$Router.push({
									name: 'friend_details',
									params: {
										friend_idx:item.user_id,
										avatar_url:item.avatar_url,
										nick_name:item.user_nickname,
										skipAgain:true,//再次进入聊天页面
										groupNickname:item.group_nickname || item.user_nickname,
									}
								});
								return
							}
						}catch(e){}
						this.$Router.push({
							name: 'add_member_details',
							params: {
								user_id:item.user_id,
								nick_name:item.user_nickname,
								avatar_url:item.avatar_url,
								isGroupGo:true,
								groupNickname:item.group_nickname || item.user_nickname,
							}
						});
					}, 1000)
					return
				}
				if (this.selectData.includes(item.user_id)) {
					// 如果数组中包含特定值，则删除该值
					const index = this.selectData.indexOf(item.user_id);
					this.selectData.splice(index, 1);
				} else {
					// 如果数组中不包含特定值，则添加该值
					this.selectData.push(item.user_id);
				}
			},
			godetails(item) {
				this.$Router.push({
					name: 'chatGroupMsg',
					params: {
						group_id: item.group_id,
						group_name: item.group_name,
						avatar_url: item.avatar_url,
					}
				});
			}
		},
	};
</script>

<style scoped lang="scss">
	.typetag{
		white-space: nowrap;
		font-size: 20rpx;
		color: #FFFFFF;
		padding: 0 10rpx;
		height: 28rpx;
		line-height: 28rpx;
		text-align: center;
		border-radius: 10rpx;
		margin-left: 10rpx;
		background-color: #FF7676;
	}
	.searchview {
		margin: 20rpx 30rpx;
		background-color: #1e1f30;
		border-radius: 60rpx;
		padding-right: 20rpx;
	}
	.prohibitSearch{
		margin: 20rpx 30rpx;
		height: 66rpx;
		line-height: 66rpx;
		background: #60A7FF;
		border-radius: 34rpx;
		opacity: 0.5;
		font-size: 28rpx;
		color: #FFFFFF;
		text-align: center;
	}

	.groupview{
		.grouptitle{
			color: #72737e;
			font-size: 24rpx;
		}
		.listitem {
			display: flex;
			align-items: center;
			padding: 20rpx 30rpx;
			position: relative;
			background-color: #1E1F30;
			&:first-of-type {
				border-radius: 20rpx 20rpx 0 0; /* 例如设置 10px 的圆角 */
				margin-top: 10rpx;
			}
			&:last-of-type {
				border-radius: 0 0 20rpx 20rpx; /* 例如设置 10px 的圆角 */
			}
			/* 处理只有一个 .listitem 的情况 */
			&:first-of-type:last-of-type {
			    border-radius: 20rpx; /* 设置所有圆角 */
			}
			&__left{
				display: flex;
				align-items: center;
				margin-right: 20rpx;
			}
			&__right {
				
				flex: 1;
				display: flex;
				align-items: center;
				&__view{
					margin-left: 20rpx;
					&__nickname {
						color: #fff;
						font-size: 28rpx;
						display: flex;
						align-items: center;
					}
					&__id {
						color: #595A66;
						font-size: 24rpx;
					}
				}
			}
		}
	}
</style>